<template>
  <el-menu
    :default-active="activeMenu"
    mode="horizontal"
    @select="handleMenuSelect"
  >
    <el-menu-item index="/shop">商城</el-menu-item>
    <el-menu-item index="/edu">农教</el-menu-item>
    <el-menu-item index="/community">社区</el-menu-item>
  </el-menu>
</template>

<script setup>
import { ref, watch } from 'vue';
import { useRoute, useRouter } from 'vue-router';

const route = useRoute();
const router = useRouter();
const activeMenu = ref(route.path);

watch(
  () => route.path,
  (newPath) => {
    activeMenu.value = newPath;
  }
);

const handleMenuSelect = (key) => {
  if (typeof key === 'string') {
    router.push(key).catch(err => {
      // 忽略重复导航错误
      if (!err.message.includes('Avoided redundant navigation')) throw err;
    });
  } else {
    console.error('Invalid key type:', key);
  }
};
</script>
